/**
 * 
 */
package org.compiere.process;

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.Properties;
import java.util.TimeZone;
import java.util.logging.Level;

import org.compiere.model.MBPartner;
import org.compiere.model.MBSCAction;
import org.compiere.model.MBSCNetWorkDiag;
import org.compiere.model.MBSCNetWorkDiagLine;
import org.compiere.model.MBSCNetWorkDiagSubLine;
import org.compiere.model.MBSCResponsibleExecutor;
import org.compiere.model.MClient;
import org.compiere.model.MUser;
import org.compiere.util.DB;
import org.compiere.util.Env;
import org.compiere.util.Msg;

/**
 * @author A.Kulantayev
 *
 */
public class NWD_SendMail extends SvrProcess {

	/** Current context */
	private Properties m_ctx;
	@Override
	protected void prepare() {

	}

	@Override
	protected String doIt() throws Exception {
		String result="";
		m_ctx = Env.getCtx();
		Timestamp currentDate = new Timestamp(System.currentTimeMillis());
		int currentDay = new org.joda.time.DateTime(currentDate.getTime()).getDayOfMonth();
		int currentMonth = new org.joda.time.DateTime(currentDate.getTime()).getMonthOfYear();
		int currentYear = new org.joda.time.DateTime(currentDate.getTime()).getYear();
		Timestamp closePeriod1 = Timestamp.valueOf(String.valueOf(currentYear)+"-06-26 10:10:10.0");
		Timestamp closePeriod2 = Timestamp.valueOf(String.valueOf(currentYear)+"-10-14 10:10:10.0");
		Timestamp closePeriod3 = Timestamp.valueOf(String.valueOf(currentYear)+"-01-04 10:10:10.0");
		Calendar lastDate=Calendar.getInstance(TimeZone.getTimeZone("GMT"));
		lastDate.setTime(currentDate);
		int lastDay = lastDate.getActualMaximum(Calendar.DAY_OF_MONTH);
		int cp1Day = new org.joda.time.DateTime(closePeriod1.getTime()).getDayOfMonth(),
			cp2Day = new org.joda.time.DateTime(closePeriod2.getTime()).getDayOfMonth(), 
			cp3Day = new org.joda.time.DateTime(closePeriod3.getTime()).getDayOfMonth();
		
		int cp1Month = new org.joda.time.DateTime(closePeriod1.getTime()).getMonthOfYear(), 
			cp2Month = new org.joda.time.DateTime(closePeriod2.getTime()).getMonthOfYear(), 
			cp3Month = new org.joda.time.DateTime(closePeriod3.getTime()).getMonthOfYear();
		
		int cp1Year = new org.joda.time.DateTime(closePeriod1.getTime()).getYear(), 
			cp2Year = new org.joda.time.DateTime(closePeriod2.getTime()).getYear(), 
			cp3Year = new org.joda.time.DateTime(closePeriod3.getTime()).getYear();
		
		//Проверяем не пришло ли время первого периода
		if((currentYear == cp1Year && currentMonth == cp1Month && currentDay == cp1Day)
				||(currentYear == cp2Year && currentMonth == cp2Month && currentDay == cp2Day)
				||(currentYear == cp3Year && currentMonth == cp3Month && currentDay == cp3Day)||(currentDay==lastDay)){
			sendAlertMail();
			result = Msg.translate(m_ctx, "Success");
			
		} 
		else
		{
			//sendAlertMail();
			result = "Проверка прошла успешно(время закрытия периода еще не пришло)";
		}
				
		return result;
	}

	private boolean sendAlertMail(){
		
		MBSCNetWorkDiag[] bsc_NetWorkDiags = getNetWorkDiag();
		for(int i = 0; i < bsc_NetWorkDiags.length; i++){
			try{
				sendMailAction(bsc_NetWorkDiags[i]);
			}
			catch(Exception e){
				e.printStackTrace();
			}
			
		}
		return true;
	}
	
	private boolean sendMailAction(MBSCNetWorkDiag netWorkDiag) throws Exception{
		
		MClient mClient = new MClient(getCtx(), Env.getAD_Client_ID(getCtx()), get_TrxName());
		
		MBSCNetWorkDiag mbscNetWorkDiag = netWorkDiag;
		
		String emailTitle ="Напоминание об отчетном периоде(Сетевой график)";
		String emailText ="";
					
		String[] recipientEmails = getRecipientEmails(netWorkDiag.getBSC_NetWorkDiag_ID());
		
		for(int i = 0; i < recipientEmails.length; i++)
		{
			String actionList = "";
			String recipientName = "";
			MBSCNetWorkDiagLine[] mbscNetWorkDiagLines = mbscNetWorkDiag.getLines(false);
			int nn=1;
			for(MBSCNetWorkDiagLine line : mbscNetWorkDiagLines){
				for(MBSCNetWorkDiagSubLine subline: line.getSubLines(false) ){
					for(MBSCAction action: subline.getActions(false)){
						for(MBSCResponsibleExecutor responsibleExecutor: action.getResponsible_Executors(false)){
							if(responsibleExecutor.getEMail().equals(recipientEmails[i])){
								if(nn!=1)
									actionList = actionList+"\n";
								actionList = actionList+nn+". "+action.getName();
								
								recipientName = responsibleExecutor.getName();
								nn++;
							}
						}
					}
				}
			}
			
			emailText = emailTitle+"\nУважаемый(ая), "+recipientName
					+".\nПредстоит закрытие отчетного периода. Не забудьте проставить статусы исполнения мероприятий в документе №"
					+mbscNetWorkDiag.getDocumentNo()+"\n\nСписок мероприятий:\n"+actionList;
						
			if(!recipientEmails[i].contains(";"))
			{
				mClient.sendEMail(recipientEmails[i], emailTitle, emailText, null);
				System.out.println(emailTitle+"\n\n"+emailText);
			}
			else
			{
				String[] recipientSubEmails = recipientEmails[i].split(";");
				for(int j = 0; j< recipientSubEmails.length; j++)
				{
					mClient.sendEMail(recipientSubEmails[i], emailTitle, emailText, null);
					System.out.println(emailTitle+"\n\n"+emailText);
				}
			}
			
			
		}
		return true;
	}
	
	private MBSCNetWorkDiag[] getNetWorkDiag(){
		
		MBSCNetWorkDiag bsc_NetWorkDiag = null;
		List<MBSCNetWorkDiag> list = new ArrayList<MBSCNetWorkDiag>();
		PreparedStatement pstmt = null;
		ResultSet rs = null;
		String sql = "SELECT bsc_networkdiag_id FROM bsc_networkdiag " +
				     "\n WHERE AD_Client_ID = " + Env.getAD_Client_ID(getCtx())+
				     "\n AND IsActive = 'Y' AND DocStatus = 'AP'";
		try{
			pstmt = DB.prepareStatement(sql, get_TrxName());
			rs = pstmt.executeQuery();
			while(rs.next()){
				bsc_NetWorkDiag = new MBSCNetWorkDiag(getCtx(), rs.getInt(1), get_TrxName());
				list.add(bsc_NetWorkDiag);
				bsc_NetWorkDiag = null;
			}
			
		}
		catch(Exception e){
			log.log(Level.SEVERE, sql.toString(), e);
		}
		finally{
			DB.close(rs, pstmt);
			rs = null; pstmt = null;
		}
		
		return list.toArray(new MBSCNetWorkDiag[list.size()]);
	}
		
	private String[] getRecipientEmails(int BSCNetWorkDiag_ID){
		
		PreparedStatement pstmt = null;
		ResultSet rs = null;
		String email = null;
		List<String> list = new ArrayList<String>();
		String 	sql = "SELECT email FROM bsc_responsible_executor"+ 
						"\nWHERE email IS NOT NULL AND bsc_action_id IN (SELECT bsc_action_id FROM bsc_action"+
							"\nWHERE bsc_networkdiagsubline_id IN(SELECT bsc_networkdiagsubline_id FROM bsc_networkdiagsubline"+ 
								"\nWHERE bsc_networkdiagline_id IN (SELECT bsc_networkdiagline_id FROM bsc_networkdiagline"+ 
									"\nWHERE bsc_networkdiag_id ="+BSCNetWorkDiag_ID+")))"+
					"\nGROUP BY email";
		try{
			pstmt = DB.prepareStatement(sql, get_TrxName());
			rs = pstmt.executeQuery();
			while(rs.next()){
				email = new String(rs.getString(1));
				list.add(email);
				email = null;
			}
		}catch(Exception e){
			log.log(Level.SEVERE, sql.toString(), e);
		}finally{
			DB.close(rs, pstmt);
			rs = null; pstmt =null; 
		}
		
		return list.toArray(new String[list.size()]);
	}

}
